package player.ui.browse;

import java.awt.Component;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.HashSet;
import java.util.Iterator;

import javax.swing.SwingUtilities;

import player.PS;
import player.mplayer.MPlayerControl;

public class VisualGroup {
	HashSet<Component> CTable=new HashSet<Component>();
	VisualGroup(){
		new Thread(){
			public void run(){
				while(true){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					SwingUtilities.invokeLater(new Runnable(){

						public void run() {
							boolean visible=checkHaveLogin();
							if(!MPlayerControl.isPlaying
									|(MPlayerControl.isPlaying&MPlayerControl.isPause)
									|PS.config.showOSD){
									visible=true;
								}
							setAllVisible(visible);
						}

					});
				
				}
			}
		}.start();
	}
	
	void add(Component cp){
		CTable.add(cp);
	}
	
	boolean checkHaveLogin(){
		boolean b=false;
		Iterator<Component> it=CTable.iterator();
		while(it.hasNext()){
			Component cp=it.next();
			boolean b2=isLoginCP(cp);
			if(b2){
				b=true;
				break;
			}
		}
		return b;
	}
	
	boolean isLoginCP(final Component cp){
		boolean b=false;
		//cp.setVisible(true);
		Point p=MouseInfo.getPointerInfo().getLocation();
		SwingUtilities.convertPointFromScreen(p, cp);
		Rectangle recTop=cp.getBounds();
		recTop.x=0;
		recTop.y=0;

		Rectangle pr=new Rectangle();
		pr.x=p.x;
		pr.y=p.y;
		Point p2=cp.getMousePosition();
		if(SwingUtilities.isRectangleContainingRectangle(recTop, pr)){
			b=true;
		}
		return b;
	}
	
	void setAllVisible(boolean vislble){
		Iterator<Component> it=CTable.iterator();
		while(it.hasNext()){
			Component cp=it.next();
			if(vislble){
				if(!cp.isVisible()){
					cp.setVisible(true);
				}
			}else{
				if(cp.isVisible()){
					cp.setVisible(false);
				}
			}
		}
	}
	
}
